﻿using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;
using YeqianFramework.common;
using YeqianFramework.core;

namespace YeqianFramework.core
{
	public delegate void StandMessageCallback(KeyValuePair kv);

	public class MessageCenter : MonoBehaviourSingleton<MessageCenter>
	{
		private Dictionary<string, StandMessageCallback> messages = new Dictionary<string, StandMessageCallback>();
		
		/// <summary>
		/// 添加消息监听
		/// </summary>
		/// <param name="msg"></param>
		/// <param name="callback"></param>
		public void AddListener(string msg, StandMessageCallback callback)
		{
			if (!messages.ContainsKey(msg))
			{
				messages.Add(msg, i => { });
			}

			messages[msg] += callback;
		}

		/// <summary>
		/// 将回调从这个消息中移除
		/// </summary>
		/// <param name="msg"></param>
		/// <param name="callback"></param>
		public void RemoveListener(string msg, StandMessageCallback callback)
		{
			if (!messages.ContainsKey(msg))
			{
				throw new KeyNotFoundException("未找到消息名：" + msg);
			}

			messages[msg] -= callback;
		}

		/// <summary>
		/// 发送消息
		/// </summary>
		/// <param name="msg"></param>
		/// <param name="kv"></param>
		public void SendMyMessage(string msg, KeyValuePair kv)
		{
			if (!messages.ContainsKey(msg))
			{
				messages.Add(msg, i => { });
			}

			foreach (StandMessageCallback item in messages[msg].GetInvocationList())
			{
				try
				{
					item(kv);
				}
				catch (System.Exception)
				{
					Debug.LogError("这里");
				}
			}
		}

		protected override void Init()
		{
			//Debug.Log("MessageCenter 初始化");
		}
	}
}
